import com.sun.jdi.connect.Connector;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * UDP 回显客户端
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private int requestPort = 0;
    private String requestIp = "";
    public UdpEchoClient(int port,String ip) throws SocketException {
        this.requestIp = ip;
        this.requestPort = port;
        // 此处我们不分配端口号,是因为防止端口号冲突,就由操作系统来自动分配
        this.socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("-> ");
            // 1. 从控制台读取数据,作为请求
            String request = scanner.nextLine();
            // 2. 把请求内容构造成 DatagramPacket 对象, 发给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length
                    ,InetAddress.getByName(requestIp),requestPort);
            socket.send(requestPacket);
            // 3. 尝试读取服务器,返回响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4093],4093);
            socket.receive(responsePacket);
            // 4. 把响应,转换成字符串,并显示出来
            String reponse = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(reponse);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient(9090,"127.0.0.1");
        udpEchoClient.start();
    }
}
